package com.ruoyi.ai.controller;


import com.alibaba.dashscope.aigc.generation.GenerationResult;

import com.ruoyi.ai.service.LargeModelService;
import com.ruoyi.common.core.web.controller.BaseController;

import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@Slf4j
@RestController
@RequestMapping("/daily_tasks")
public class DailyTasksController extends BaseController
{
    @Autowired
    private LargeModelService largeModelService;


    /**
     * 流式输出接口，浏览器可以分块接收（类似于chat gpt动态生成效果）
     */
    @GetMapping(value = "/stream/check_answer", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<?> target(@RequestParam("question") String question,  @RequestParam("answer") String answer) {
        if (!StringUtils.hasLength(question)||!StringUtils.hasLength(answer)) {
            return Flux.error(new IllegalArgumentException("question/answer is empty"));
        }
        try {
            Flowable<GenerationResult> conversationResultFlowable = largeModelService.streamCheckAnswer(question, answer);
            return Flux.from(conversationResultFlowable)
                    //只推送增量的部分
                    .map(result -> result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (Exception e) {
            log.error("server error{}", e.getMessage());
            return Flux.error(e);
        }
    }

}
